<template>

  <!-- 展示所有账户的交易单元 -->
  <ContentWrap>
      <div class="transaction-container">
        <div 
          v-for="(account, index) in queryFormRefUnit" 
          :key="index" 
          class="account-card"
        >
          <h3 class="account-title">{{account.account}}</h3>
          
          <!-- 交易名称 -->
          <div class="transaction-item">
            <span class="label"></span>
             <!-- 改为按钮 -->
             <button 
                class="holdings-btn"
                @click="getList(account.tradingUnitDOS)"
              >
                查看持仓
              </button>
          </div>

          <!-- 持仓信息 -->
          <div class="holdings-section">
            <div class="transaction-item">
              <span class="label">交易名称</span>
              <span class="value">
              {{ account.tradingUnitDOS && account.tradingUnitDOS.length > 0 ? account.tradingUnitDOS[0].name : '暂无数据' }}
            </span>
          
              <span class="update-time">上次更新时间：
                {{formatTime( account.tradingUnitDOS && account.tradingUnitDOS.length > 0 ? account.tradingUnitDOS[0].updateTime : '暂无数据') }}
              </span>
            </div>
            <br/>
            <!-- 交易单元 -->
            <div class="transaction-units">
              <span 
                v-for="(unit, unitIndex) in account.tradingUnitDOS"
                :key="unitIndex"
                class="unit-tag"
              >
                {{ unit.tradingUnit }}
              </span>
            </div>
          </div>
        </div>
      </div>
  </ContentWrap>
  
  <!-- 弹窗 -->
  <el-dialog v-model="dialogVisible" title="查看持仓" width="80%" style="height: 75vh; max-height: 90%; overflow: auto;">

    <!-- 交易单元按钮 -->
    <br/>
    <div class="dashboard-container" v-for="(account, index) in buttonList" :key="index" >
    <!-- 高耗能按钮 -->
      <button 
        class="status-card high-consumption"
      
      >
        <div class="card-header">
          <span style="color:#fff;">{{ account.tradingUnit }}</span>
        </div>
      </button>
    </div>
    <br/>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="70px"
    >
      <el-form-item label="时段" prop="dayTime">
        <el-date-picker
          v-model="queryParams.dayTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>

      </el-form-item>
    </el-form>

    <!-- 列表 -->
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="序号" align="center">
        <template #default="{ $index }">
          {{ $index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="时段" align="center">
        <template #default="{ row }">
          <span :style="{ color: getTimePeriodColor(row.timePeriod) }">
            {{ row.timePeriod }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="待操作转入MWh" align="center" prop="pendingTransferIn" />
      <el-table-column label="系统可卖量MWh" align="center" prop="systemBuyableQuantity" />
      <el-table-column label="待操作转出MWh" align="center" prop="pendingTransferOut" />
      <el-table-column label="实际可卖量MWh" align="center">
      <template #default="{ row }">
        {{ Number(row.actualSellableQuantity).toFixed(3) }}
      </template>
    </el-table-column>
    </el-table>
    <!-- 分页 -->
    <!-- <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="handleQuery"
    /> -->
  </el-dialog>

  <!-- 表单弹窗：添加/修改 -->
  <PositionForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { PositionApi, PositionVO } from '@/api/dd/position'
import { TradingUnitApi, TradingUnitVO } from '@/api/dd/tradingunit'
import PositionForm from './PositionForm.vue'

/** 持仓数据 列表 */
defineOptions({ name: 'Position' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<PositionVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 30,
  timePeriod: undefined,
  systemBuyableQuantity: undefined,
  pendingTransferIn: undefined,
  actualBuyableQuantity: undefined,
  systemSellableQuantity: undefined,
  pendingTransferOut: undefined,
  actualSellableQuantity: undefined,
  tradingId: undefined,
  tradingName: undefined,
  createTime: [],
  dayTime: [],
})

/** 搜索表单 */
const queryUnity = reactive({
  state: 0
})
// 搜索表单的ref
const queryFormRef = ref() // 搜索的表单
// 搜索表单的ref
const queryFormRefUnit = ref() // 单元信息

const exportLoading = ref(false) // 导出的加载中
// 弹窗的显示状态
const dialogVisible = ref(false);


// 时间戳格式化函数
const formatTime = (timestamp) => {
  const date = new Date(timestamp);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  }

//按钮
const buttonList = ref()

/** 查询列表 */
const getList = async (tradingUnitDOS) => {
  loading.value = true
  dialogVisible.value = true; // 打开弹窗
  buttonList.value = tradingUnitDOS; // 设置交易名称
  if(tradingUnitDOS && tradingUnitDOS.length > 0){
    try {
      queryParams.tradingId = tradingUnitDOS[0].id; // 设置交易ID
      const data = await PositionApi.getPositionSumList(queryParams)
      console.log(data)
      list.value = data
      // total.value = data.total
    } finally {
      loading.value = false
    }
  }
  
}

// 单元查询列表
const getListUnit = async () => {
  loading.value = true
  try {
    const data = await TradingUnitApi.getTradingUnitSelectMap(queryUnity)
    queryFormRefUnit.value = data
  } finally {
    loading.value = false
  }
}


/** 搜索按钮操作 */
const handleQuery = async () => {
    try {
      const data = await PositionApi.getPositionSumList(queryParams)
      list.value = data
    } finally {
      loading.value = false
    }
  
}

/** 重置按钮操作 */
const resetQuery = () => {
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await PositionApi.deletePosition(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

// 按钮点击处理方法
const handleHighConsumption = async (tradingUnit) => {

    try {
      queryParams.tradingId = tradingUnit; // 设置交易ID
      const data = await PositionApi.getPositionPage(queryParams)
      list.value = data.list
      total.value = data.total
    } finally {
      loading.value = false
    }
  
  
}
// 根据时段返回对应的颜色
const getTimePeriodColor = (timePeriod: string) => {
  const peakPeriods = ['07:00-08:00','08:00-09:00', '17:00-18:00', '18:00-19:00', '19:00-20:00', '20:00-21:00', '21:00-22:00', '22:00-23:00'];
  const offPeakPeriods = ['09:00-10:00', '10:00-11:00', '11:00-12:00', '12:00-13:00', '13:00-14:00', '14:00-15:00', '15:00-16:00', '16:00-17:00'];
  const valleyPeriods = ['00:00-01:00', '01:00-02:00', '02:00-03:00', '03:00-04:00', '04:00-05:00', '05:00-06:00', '06:00-07:00', '23:00-24:00'];

  if (peakPeriods.includes(timePeriod)) {
    //绿色
    return 'red'; // 高峰时段颜色
  } else if (offPeakPeriods.includes(timePeriod)) {
    return 'green'; // 平峰时段颜色
  } else if (valleyPeriods.includes(timePeriod)) {

    //橘色
    return 'orange'; // 低谷时段颜色
  }
};

/** 初始化 **/
onMounted(() => {
  // getList()
  getListUnit()
  // 计算当月的开始日期和结束日期
  const now = new Date();
  const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);
  const endOfMonth = new Date(now.getFullYear(), now.getMonth() + 1, 0);
  const formattedStartOfMonth = formatTime(startOfMonth.getTime());
  const formattedEndtOfMonth = formatTime(endOfMonth.getTime());
  console.log('格式化后的当月开始日期:', formattedStartOfMonth);
  // 设置默认时间为当月的开始和结束日期
  queryParams.dayTime = [formattedStartOfMonth, formattedEndtOfMonth];
})
</script>

<style scoped>
/* 新增按钮样式 */
.holdings-btn {
  padding: 6px 12px;
  background: #b9d2f8;
  border: 1px solid #b6d2ee;
  border-radius: 6px;
  color: #1a1a1a;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.2s;
  display: flex;
  align-items: center;
}

/* 按钮悬停效果 */
.holdings-btn:hover {
  background: #e6ebf0;
  border-color: #a8b1bb;
}

/* 按钮激活效果 */
.holdings-btn:active {
  background: #dde2e7;
}

/* 调整原布局间距 */
.transaction-item {
  margin-bottom: 12px; /* 原为8px */
}
/* 容器样式 */
.transaction-container {
  max-width: 600px;
  margin: 20px auto;
  font-family: Arial, sans-serif;
}

/* 账户卡片 */
.account-card {
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
  background: #fff;
}

.account-title {
  color: #333;
  font-size: 16px;
  margin: 0 0 12px 0;
  padding-bottom: 8px;
  border-bottom: 1px solid #b7e0f0;
}

/* 通用项样式 */
.transaction-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.label {
  color: #666;
  font-size: 14px;
}

.value {
  color: #333;
  font-weight: 500;
}

/* 更新时间 */
.update-time {
  color: #999;
  font-size: 12px;
}

/* 交易单元标签 */
.transaction-units {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.unit-tag {
  background: #91c5f7;
  border-radius: 4px;
  padding: 4px 8px;
  font-size: 12px;
  color: #ffffff;
}

</style>

<style scoped>
.dashboard-container {
  grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); /* 缩小最小宽度 */
  gap: 1.5rem; /* 缩小间距 */
  padding: 0.2rem;
  background-color: #f5f7f8; /* 背景色 */;
}

.status-card {
  padding: 0.4rem; /* 缩小内边距 */
  border-radius: 8px; /* 减小圆角 */
  background-color: #9ed9f7; /* 背景色 */;
  /* 添加边框样式 */
  border: 1px solid #ffffff; 
}

.card-header h2 {
  font-size: 1.0rem; /* 缩小标题字号 */
  margin-bottom: 0.1rem;
}

.card-value {
  font-size: 2.5rem; /* 缩小数值字号 */
}

/* 保持颜色方案和交互效果 */
.status-card:hover {
  transform: translateY(-1px); /* 减小悬停位移 */
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.12);
}
</style>